package cn.tedu.client.service.impl;

import cn.tedu.base.response.JsonResult;
import cn.tedu.base.response.StatusCode;
import cn.tedu.base.utils.HashPasswordUtil;
import cn.tedu.base.utils.JWTUtil;
import cn.tedu.base.utils.SnowFlakeUtil;
import cn.tedu.client.constant.StatusConstant;
import cn.tedu.client.dao.mapper.ClientMapper;
import cn.tedu.client.dao.mapper.WalletMapper;
import cn.tedu.client.pojo.dto.ClientRegisterDTO;
import cn.tedu.client.pojo.dto.ClientUpdateDTO;
import cn.tedu.client.pojo.entity.Client;
import cn.tedu.client.pojo.entity.Wallet;
import cn.tedu.client.pojo.vo.ClientInfoVO;
import cn.tedu.client.pojo.vo.ReceiverVO;
import cn.tedu.client.service.ClientService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ClientServiceImpl implements ClientService {

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private WalletMapper walletMapper;

    /*
     * 1、clientRegisterDTO接收用户的信息
     * 2、取出用户输入的名字与数据库进行比较，查看是否已经存在
     *   2.1 如果存在，则直接返回当前用户名以存在，请更换
     *   2.2 如果不存在，则进行之后的步骤
     * 3、根据用户输入信息在数据库中创建新的用户
     * */
    @Override
    public String register(@RequestBody ClientRegisterDTO clientRegisterDTO) {
        log.debug("用户输入信息二次展示：clientRegisterDTO:{}", clientRegisterDTO);
        String resultMsg;
        if (StringUtils.isEmpty(clientRegisterDTO.getPhoneNum()) || StringUtils.isEmpty(clientRegisterDTO.getPassword())) {
            resultMsg = "手机号或密码为空，请输入";
            return resultMsg;
        } else {
            //取出用户输入的名字，查看数据库中是否有对应的数据
            String clientPhoneNum = clientRegisterDTO.getPhoneNum();
            //创建条件构造器
            QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
            clientQueryWrapper.select("id", "phone_num")
                    .eq("phone_num", clientPhoneNum);
            List<Client> clients = clientMapper.selectList(clientQueryWrapper);
            //进行判断是否有对应的用户
            if (!clients.isEmpty()) {
                //不为空说明已经有对应的用户了
                resultMsg = StatusConstant.PHONENUM_ISEXIST  ;
                return resultMsg;
            } else {
                //为空，说明不曾有对应的用户，根据用户传入信息进行注册
                Client newClient = new Client();
                BeanUtils.copyProperties(clientRegisterDTO, newClient);
                /*
                 * 进行密码加密,并设置
                 * */
                newClient.setPassword(HashPasswordUtil.hashPassword(newClient.getPassword()));
                newClient.setUserLevel((byte) 1);
                //雪花算法生成随机的钱包id
                Long snowId = SnowFlakeUtil.getId();
                newClient.setWalletId(snowId);
                newClient.setUserProfile("这个人很懒什么也没说");
                newClient.setCreateTime(new Date());
                //进行存储
                int clientRegisterResult = clientMapper.insert(newClient);

                /*
                 * 用户表中注册完成后需要相应数据添加到c包表中
                 * */
                //1、获取用户id
                Integer userId = clientMapper.selectIdByUsername(newClient.getUsername());
                //2、创建用户对应的钱包表数据
                Wallet wallet = new Wallet();
                wallet.setId(newClient.getWalletId());
                wallet.setUserId(userId);
                wallet.setUsername(newClient.getUsername());
                wallet.setCreateTime(new Date());
                int walletRegisterResult = walletMapper.insert(wallet);

                if (clientRegisterResult != 1 && walletRegisterResult != 1) {
                    resultMsg = StatusConstant.REGISTER_FAIL;
                    return resultMsg;
                } else {
                    resultMsg = StatusConstant.REGISTER_SUCCESS;
                    return resultMsg;
                }
            }
        }
    }


//    @Override
//    public JsonResult loadInfo(HttpServletRequest request) {
//        String authorization = request.getHeader("Authorization");
//        String visitToken;
//        if (authorization != null) {
//            visitToken = authorization.substring(7);
//            log.debug("visitToken:{}",visitToken);
//            Map<String, Object> userInfo = JWTUtil.getUserInfo(visitToken);
//            Object object = userInfo.get("userInfo");
//            String objectString = (String) object;
//            Client client = JSON.parseObject(objectString, Client.class);
//            System.out.println(client);
//            log.debug("client:{}",client);
//            Client clientInfo = clientMapper.selectById(client.getId());
//            log.debug("userInfo:{}",userInfo);
//            return new JsonResult(StatusCode.OPERATION_SUCCESS,clientInfo);
//        } else {
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
//    }

    @Override
    public JsonResult loadInfo(Long id){
        //通过前端传入的id来查询数据库中的数据
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        clientQueryWrapper.select("id", "user_name", "phone_num","user_email","wallet_id","user_photo")
                .eq("id", id);
        List<Client> clients = clientMapper.selectList(clientQueryWrapper);
        Client client = clients.get(0);
        ClientInfoVO clientInfoVO = new ClientInfoVO();
        BeanUtils.copyProperties(client,clientInfoVO);
        log.debug("clientInfoVO:{}",clientInfoVO);
        return new JsonResult(StatusCode.OPERATION_SUCCESS,clientInfoVO);
    }

    @Override
    public JsonResult update(ClientUpdateDTO clientUpdateDTO) {
        Client client = new Client();
        client.setId(clientUpdateDTO.getId());
        BeanUtils.copyProperties(clientUpdateDTO,client);
        log.debug("client:{}",client);
        client.setUpdateTime(new Date());
        UpdateWrapper<Client> clientUpdateWrapper = new UpdateWrapper<>();
        clientUpdateWrapper.eq("id",client.getId());
        int result = clientMapper.update(client, clientUpdateWrapper);

        if (result > 0) {
            return new JsonResult(StatusCode.OPERATION_SUCCESS);
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @Override
    public ReceiverVO getReceiver(Integer userId) {
        log.debug("服务接收查询收款人参数:{}",userId);
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        Client client = clientMapper.selectOne(queryWrapper);
        ReceiverVO receiverVO = new ReceiverVO();
        receiverVO.setUsername(client.getUsername());
        receiverVO.setUserPhoto(client.getUserPhoto());
        return receiverVO;
    }
}